package com.pic.mgt.monitor;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.pic.mgt.monitor.parser.FormatParser;
import com.pic.mgt.unit.Message;
import com.pic.mgt.unit.Unit;

public abstract class MessageUnitConverter extends UnitConverter {
	
	protected Message message;
	
	protected FormatParser messageTransactionFileParser;
	protected FormatParser confirmtaionFileForTxFileParser;
	
	@Override
	protected void parseUnitTypeContent(Unit unit)
									throws IOException,
										   WrongUnitFormatException {
		this.message = (Message)unit;
		
		// 分析並填入單元型態的內容(第二層級)
		doFill();
		
		// 分析並填入集配信型態的內容(第三層級)
		parseIGXTypeContent(this.message);
	}
	
	/*
	 * 放入訊息型態內容資訊:
	 * (1) Transaction File
	 * (2) Transaction Date
	 * (3) Confirmation File For Tx File
	 */
	private void doFill() throws WrongUnitFormatException {
		// --------------------- (1) Transaction File ---------------------
		// throws WrongUnitFormatException
		fillTransactionFile();
		
		// --------------------- (2) Transaction Date ---------------------
		// throws WrongUnitFormatException
		fillTransactionDate();
		
		// --------------------- (3) Confirmation File For Tx File ---------------------
		// throws WrongUnitFormatException
		fillConfirmationFileForTxFile();
	}
	
	protected void fillTransactionFile() throws WrongUnitFormatException {
		try {
			File transactionFile = (File)
				this.messageTransactionFileParser.
						parse(super.confirmationFile);
			this.message.setTransactionFile(transactionFile);
		} catch (WrongUnitFormatException e) {
			if (e.getMessage().indexOf("doesn't exist") >= 0 ) {
				// 如果是找不到交易的檔案，則忽略（只有訊息是如此！）
			}
			else {
				throw e;
			}
		}
	}
	
	private void fillTransactionDate() throws WrongUnitFormatException {
		this.message.setTransactionTime(new Date());
	}
	
	protected void fillConfirmationFileForTxFile() throws WrongUnitFormatException {
		try {
			this.message.setConfirmationFileForTxFile((File)
					this.confirmtaionFileForTxFileParser.parse(super.confirmationFile));
		} catch (WrongUnitFormatException e) {
			if (e.getMessage().indexOf("doesn't exist") >= 0 ) {
				// 如果是找不到交易檔的確認檔，則忽略（只有訊息是如此！）
			}
			else {
				throw e;
			}
		}
	}
	
	protected abstract void parseIGXTypeContent(Unit unit)
											throws IOException,
												   WrongUnitFormatException;
	
	// --- getter and setter ---
	
	public void setMessageTransactionFileParser(
			FormatParser messageTransactionFileParser) {
		this.messageTransactionFileParser = messageTransactionFileParser;
	}

	public void setConfirmtaionFileForTxFileParser(
			FormatParser confirmtaionFileForTxFileParser) {
		this.confirmtaionFileForTxFileParser = confirmtaionFileForTxFileParser;
	}
	
}
